// subPages/equipment/sleepIndx/sleepIndx.js
const app = getApp();
var util = require('../../../utils/util');
var utils =  require('../../../utils/healthUtil.js');
var json =  require('../../../data/json.js');
let LineChart = null
import * as echarts from '../../../ec-canvas/echarts';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mainType: 1,
    dateType: 0, //0日1周2月
    navDateList: json.navDateList,
    statisticalList: json.statisticalList,
    sleepList: json.sleepList,
    statisticalType: 0,
    ec: {
      // lazyLoad: true // 延迟加载
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if(options.user_id){
      that.setData({
        userId: options.user_id
      })
      that.getDevice(that.data.userId)
      that.setDate()
      that.getData()
      that.startSetInter()
    }
  },

  //获取设备id
  getDevice: function(userId){
    if(userId){
      var that = this
      util.getAjax(app.globalData.apiUrl +'/get_user_bd',function(res){
        console.log(res)
        if(res.data.length != 0){
          var deviceID = ''
          for(var i in res.data){
            if(res.data[i].type == '3'){
              deviceID = res.data[i].eid
              break;
            }
          }
          if(deviceID){
            that.getDeviceStatus(deviceID)
            that.setData({
              deviceID: deviceID
            })
          }
        }else{
            console.log('no_id');
            util.showModelAll('提示','请先绑定设备',function(){
                wx.navigateTo({
                    url: '/subPages/mine/myDevice/myDevice',
                })
            },function(){
                wx.navigateBack({
                    delta: 1, // 回退前 delta(默认为1) 页面
                })
            })
        }
      },{userid: userId})
    }
  },

  //获取设备是否在线
  getDeviceStatus:function(deviceID){
    if(deviceID){
      var that = this
      util.getAjax(app.globalData.apiUrl +'/Api/Sleep/getdevstatus',function(res){
        // console.log(res)
        if(res.data.data.status == 'online'){
          that.setData({
            isOnline: true
          })
        }else{
          that.setData({
            isOnline: false
          })
        }
      },{iemi: deviceID})
    }
  },

  //左选择日期
  leftDate:function(e){
    var that = this
    that.setData({
      date: utils.leftDate(that.data.date,e.currentTarget.dataset.type)
    })
    that.setDateList(that.data.dateType)
    that.getStatisticalList()
  },

  //右选择日期
  rightDate:function(e){
    var that = this
    that.setData({
      date: utils.rightDate(that.data.date,e.currentTarget.dataset.type)
    })
    that.setDateList(that.data.dateType)
    that.getStatisticalList()
  },

  //设置日期
  setDate:function(){
    var that = this
    let date = util.setTime(new Date()-1*24*3600*1000)
    let Y = date.split('-')
    that.setData({
      date: date,
      dateStart: Y[0]- 3,
      dateEnd: date,
      dateList: [date]
    })
  },

  bindDateChange: function(e) {
    var that = this
    that.setData({
      date: e.detail.value,
    })
    that.setDateList(that.data.dateType)
    that.getStatisticalList()
  },

  //切换
  typeBtn:function(e){
    var that = this
    var mainType = e.currentTarget.dataset.type;
    if (that.data.mainType == mainType) {
      return false;
    } else {
      that.setData({
        mainType: mainType
      })
      switch (mainType) {
        case '1':
          break;
        case '2':
          that.getStatisticalList()
          break;
      }
    }
  },

  startSetInter: function(){
    var that = this;
    //将计时器赋值给setInter
    that.data.setInter = setInterval(function(){
      that.getData();
    }, 20000);
  },

  endSetInter: function(){
    var that = this;
    //清除计时器  即清除setInter
    clearInterval(that.data.setInter)
  },

  //获取实时数据
  getData:function(){
    var that = this
    util.getAjax(`${app.globalData.apiUrl}/Api/Sleep/q_get`,function(res){
      console.log(res)
      var sleepList = json.sleepList
      if(res.data.content && res.data.content.payload){
        let list =  res.data.content.payload
        for(var i in sleepList){
          switch (sleepList[i].text) {
            case '心率':
              sleepList[i].data = list.onBed?list.heartBeat:'-'
              break;
            case '呼吸率':
              sleepList[i].data = list.onBed?list.respiratoryRate:'-'
              break;
            case '体动':
              sleepList[i].data = util.setTime5(list.sendDateTime / 1000)
              break;
          }
        }
        that.setData({
          sleepList: sleepList
        })
      }
    },{iemi: that.data.deviceID,type: 1})
  },

  //获取统计数据
  getStatisticalList:function(){
    var that = this
    let date = (new Date(String(that.data.date).replace(/-/g,"/")).getTime())/1000
    let nowDate =  (new Date(String(util.setTime(new Date())).replace(/-/g,"/")).getTime())/1000
    if(date < nowDate){
      util.getAjax(`${app.globalData.apiUrl}/Api/Sleep/getdaystatsbydevid`,function(res){
        // console.log(res)
        if(res.data && res.data.length!=0){
          var statisticalDatalist = []
          var statisticalDateList = []
          for(var i in res.data){
            for(var j in res.data[i].data.data){
              // console.log(that.data.deviceID)
              // console.log(res.data[i].data.data[j].devId)              
              if(that.data.deviceID == res.data[i].data.data[j].devId){
                statisticalDatalist.push(res.data[i].data.data[j])
                statisticalDateList.push(res.data[i].date)
              }
            }
          }
          that.setData({
            isStatistical: true,
            statisticalDateList: statisticalDateList.reverse(),
            statisticalDatalist: statisticalDatalist
          })
          that.setEchartsData(that.data.statisticalType)
        }else{
          that.setData({
            isStatistical: false,
          })
        }
      },{pro: that.data.dateList})
    }else{
      that.setData({
        isStatistical: false,
      })
    }
  },

  //设置日期数组
  setDateList:function(cur){
    var that = this
    var dateList = []
    switch (cur) {
      case 0:
        //日
        dateList.push(that.data.date)
        break;
      case 1:
        //周
        for(var i=0; i<7;i++){
          let weekDate = util.setTime(new Date(new Date(that.data.date)-i*24*3600*1000))
          dateList.push(weekDate)
        }
        break;
      case 2:
        //月
        for(var i=0; i<30;i++){
          let weekDate = util.setTime(new Date(new Date(that.data.date)-i*24*3600*1000))
          dateList.push(weekDate)
        }
        break;
    }
    that.setData({
      dateList: dateList
    })
  },

  setEchartsData:function(cur){
    var that = this
    if(that.data.statisticalDatalist && that.data.isStatistical){
      var list = that.data.statisticalDatalist
      var statisticaList = []
      var title = ''
      for(var i in list){
        switch (cur) {
          case 0:
            title = '心率（次/分）'
            statisticaList.push(list[i].heartRate)
            break;
          case 1:
            title = '呼吸率（次/分）'
            statisticaList.push(list[i].respiratoryRate)
            break;
          case 2:
            title = '温度（℃）'
            statisticaList.push(list[i].temperature)
            break;
          case 3:
            title = '体动（次）'
            statisticaList.push(list[i].bodyMove)
            break;
          case 4:
            title = '睡眠时间'
            statisticaList.push(list[i].sleepHours)
            break;
          case 5:
            title = '离床次数（次）'
            statisticaList.push(list[i].bedAway)
            break;
          case 6:
            title = '异常次数（次）'
            statisticaList.push(list[i].alarm)
            break;
        }
      }
      that.setData({
        title: title,
        statisticaList: statisticaList.reverse()
      })
      that.linechartsComponnet = that.selectComponent('#mychartLine');
      LineChart = null
      that.getLineGraphData();  //创建图表
    }
  },

  //线图表
  getLineGraphData:function(){
    var that = this
    if (!LineChart){
      that.init_LineEcharts(); //初始化图表
    }else{
      that.setLineOption(); //更新数据
    }
  },

  //初始化图表
  init_LineEcharts: function () {
    var that = this
    that.linechartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      LineChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      LineChart.showLoading({
        text : '正在努力的读取数据中...'
      });
      // Chart.setLineOption(this.getLineOption());
      that.setLineOption();
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return LineChart;
    });
  },

  setLineOption: function () {
    LineChart.clear();  // 清除
    LineChart.setOption(this.getLineOption());  //获取新数据
  },

  //设置折线图表
  getLineOption: function () {
    var that = this
    // 指定图表的配置项和数据
    var option = {
      title : {
        text: that.data.title,
        textStyle: {
          color: 'white',
          fontSize: '12'
        },
        padding: 2
      },
      grid:{ 
        borderWidth:0,
        x:0,
        y:30,
        x2:0,
        y2:0,
        containLabel: true
      },
      xAxis: {
        type: 'category',
        show:true,
        boundaryGap:true,
        data : that.data.statisticalDateList,
        axisLine:{
          show:true,
          lineStyle:{
            color: 'white',
            width: 1,
          }
        },
        axisTick:{
          show:false
        },
        axisLabel:{
          show:true,
          color: 'white',
          interval: 0,
          formatter: '{value}',
          formatter:function(value){
            return utils.setTime13(value) + '日'
          }
        },
      },
      yAxis: {
        type: 'value',
        boundaryGap:false,
        show:true,
        scale: false,
        splitNumber:2,
        axisLine:{
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine:{
          show:true,
          lineStyle:{
            color: 'rgba(255,255,255,0.3)',
          }
        },
        axisLabel:{
          show: true,
          inside: true,
          verticalAlign: 'bottom',
          margin: 0,
          color: 'white',
          formatter:function(value,index){
            return value
          }
        },
      },
      dataZoom:[
        {
          show: false,
          type:'slider',
          start: utils.dataZoom(that.data.statisticalDateList),
          end: 100,
          left:'3%',
          right:'3%',
          maxValueSpan: 10,
        },
        {
          type: 'inside',
        },
      ],
      series : [{
        name:'',
        type:'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 12,
        itemStyle : {
          normal: {
            color: '#fff',
          },
        },
        emphasis:{
          label:{
            show: true,
            position: 'top',
            formatter:function(params){
              return params.data;
            }
          },
          itemStyle:{
            borderWidth: 12,
            borderType:'solid',
            borderColor: 'rgba(255,255,255,0.5)'
          }
        },
        data: that.data.statisticaList
      }]
    };
    LineChart.hideLoading()
    return option;
  },

  //切换日期
  dateBtn:function(e){
    var that = this
    var cur = e.currentTarget.dataset.type;
    if (that.data.dateType == cur) {
      return false;
    } else {
      that.setData({
        dateType: cur
      })
      that.setDateList(cur);
      that.getStatisticalList()
    }
  },

  //切换统计
  statisticalBtn:function(e){
    var that = this
    var cur = e.currentTarget.dataset.type;
    if (that.data.statisticalType == cur) {
      return false;
    } else {
      that.setData({
        statisticalType: cur
      })
      that.setEchartsData(cur);
    }
  },

  //每日报告
  clickBtn:function(){
    wx.navigateTo({
      url: '../sleepReport/sleepReport?date='+ this.data.date,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
